package Service;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.Socket;
import java.net.URL;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import org.apache.log4j.Logger;


import com.mchange.v2.sql.filter.SynchronizedFilterDataSource;

import AcceptData.ModuleConstant;
import JdbcUitils.InsertCyclingFromImeiDao;
import JdbcUitils.StringUtil;


public class ServerThread extends Thread {
	
	static String speedValue = "10";
	static String offline = "10";
	static{
		Map<String,String> globalVariableCacheMap = new HashMap<>();
		InsertCyclingFromImeiDao fromImeiDao2 = new InsertCyclingFromImeiDao();
		globalVariableCacheMap = fromImeiDao2.getGlobalVariableCacheMap();
		if(!StringUtil.isEmpty(globalVariableCacheMap.get(ModuleConstant.GLOBAL_VARIABLE_SPEED))){
			speedValue = globalVariableCacheMap.get(ModuleConstant.GLOBAL_VARIABLE_SPEED);
		}
		if(!StringUtil.isEmpty(globalVariableCacheMap.get(ModuleConstant.GLOBAL_VARIABLE_OFFLINE_TIME))){
			offline = globalVariableCacheMap.get(ModuleConstant.GLOBAL_VARIABLE_OFFLINE_TIME);
		}
		
	}
	// 和本线程相关的Socket
		Socket socket = null;
		public ServerThread(Socket socket) {
			this.socket = socket;
		}
	// 线程执行的操作，响应客户端的请求
	public void run() {
		try {
			InputStream is = null;
			InputStreamReader isr = null;
			BufferedReader br = null;
			OutputStream os = socket.getOutputStream();
			PrintWriter pw = new PrintWriter(os);
			is = socket.getInputStream();
			isr = new InputStreamReader(is);
			br = new BufferedReader(isr);
			String info = null;
			String [] road=null;
			
			//读取客户端发来的请求
			while((info = br.readLine()) != null){
				// 循环读取客户端的信息
				String[] infoSplit = null;
				info = info.replace("<", "").replace(">","");
				infoSplit = info.split(",");
				System.out.println("【"+infoSplit[0] + "】：" + info);
				if (info.length() > 80 ) {
					InsertIntoIMEIinfoFromSocketSer iinfoFromSocketSer = new InsertIntoIMEIinfoFromSocketSer();
					//判断车辆的统计状态 1 在线 2 离线 3 报警 0表示没有判断离线 在线
					//zqq:zandingshudu wei 5
					//获取全局变量的速度大小值
					//String speedValue = iinfoFromSocketSer.getspeedValueByspeedname("锁车超度报警");
					String statisticBehavior = "0";
					if(Integer.parseInt(infoSplit[8])>Integer.parseInt(speedValue)&&"0".equals(infoSplit[12])){
						//锁车且行车速度超过5
						statisticBehavior="3";
					}
					iinfoFromSocketSer.InsertIntoIMEIinfo(info+","+statisticBehavior);
					//将信息更新到每个硬件对应的最新数据的表中
					iinfoFromSocketSer.UpdateOrInsertIMEIinfonew(info,statisticBehavior,offline);
					if(!"00".equals(infoSplit[13])){
						String codeDec=iinfoFromSocketSer.getDescByFalutcode(infoSplit[13]);
						String business_id = iinfoFromSocketSer.getBusinessIdByIMEI(infoSplit[0]);
						Map<String,ArrayList<String>> ssmap = iinfoFromSocketSer.getNearlyChevkpointBybusinessId(business_id);
						ArrayList<String> listgps = ssmap.get("listgps");
						ArrayList<String> listaddress = ssmap.get("listaddress");
						TreeMap<Integer, String> treeMap = iinfoFromSocketSer.getMinDistance(infoSplit[7]+","+infoSplit[5], 1, listgps, listaddress);
						
						String[] psarr = {infoSplit[1],infoSplit[0],infoSplit[13],business_id,treeMap.firstEntry().getValue(),infoSplit[5]+","+infoSplit[7],codeDec};
						//System.out.println(Arrays.toString(psarr));
						iinfoFromSocketSer.insertIntoHardwareFault(psarr);
					}
					/*if(infoSplit[5].length()+infoSplit[7].length()<40){
					String result = connectURL("http://api.map.baidu.com/geoconv/v1/?coords=" + infoSplit[5] + ","
							+ infoSplit[7] + "&from=1&to=5&output=json&ak=HdveE6DXEvvXf9Ppl5Xjwvm73C1hecfX", "");
					String cut1 = result.substring(result.indexOf("x") + 3);
					String[] cut2 = cut1.split(",");
					String cut3 = cut1.substring(cut1.indexOf("y") + 3);
					String[] cut4 = cut3.split("}");
					l =  cut2[0]+ "," + cut4[0];
					String result2 = connectURL("http://api.map.baidu.com/geocoder/v2/?location=" +cut4[0]+ "," + cut2[0]
							+ "&output=json&ak=HdveE6DXEvvXf9Ppl5Xjwvm73C1hecfX", "");
					 road=	result2.split("\"");
					System.out.println(road[45]);
					//{"status":0,"result":{"location":{"lng":110.31800770412998,"lat":25.31193921395791},"formatted_address":"广西壮族自治区桂林市叠彩区清风路","business":"","addressComponent":{"country":"中国","country_code":0,"province":"广西壮族自治区","city":"桂林市","district":"叠彩区","adcode":"450303","street":"清风路","street_number":"","direction":"","distance":""},"pois":[],"poiRegions":[],"sematic_description":"泗洲湾花园东北90米","cityCode":142}}
					}else{
						l="0,0";
						road=null;
					}
					
					String sql1 = "INSERT INTO location_info VALUES(uuid(),?,?,?,NOW(),?,?,'"+road[45]+"')";
					//将数据插入到数据库
*/					
					System.out.println("已新增");
				}else{
					System.out.println(info);
				}
				String reply = "OK";
				pw.write(reply);
				pw.flush();
			}
			pw.close();// 输出流关闭
			socket.close();
			
			/*while ((info = br.readLine()) != null) {
				// 循环读取客户端的信息
				String[] infoSplit = null;
				String l = null;
				infoSplit = info.split(",");
				System.out.println("【"+infoSplit[0] + "】：" + info);
				if (info.length() > 85 ) {
					if(infoSplit[5].length()+infoSplit[7].length()<40){
					String result = connectURL("http://api.map.baidu.com/geoconv/v1/?coords=" + infoSplit[5] + ","
							+ infoSplit[7] + "&from=1&to=5&output=json&ak=HdveE6DXEvvXf9Ppl5Xjwvm73C1hecfX", "");
					String cut1 = result.substring(result.indexOf("x") + 3);
					String[] cut2 = cut1.split(",");
					String cut3 = cut1.substring(cut1.indexOf("y") + 3);
					String[] cut4 = cut3.split("}");
					l =  cut2[0]+ "," + cut4[0];
					}else{
						l="0,0";
					}
					con.setAutoCommit(false);//硬件，电话，基站，时间，经纬度，速度，电流，电压，备用电池电压，里程
					String sql1 = "INSERT INTO imei_info VALUES(uuid(),?,?,?,NOW(),?,?,?,?,?,0)";
					ps = con.prepareStatement(sql1);
					ps.setString(1, infoSplit[0]);//硬件
					ps.setString(2, infoSplit[1]);//电话
					ps.setString(3, infoSplit[2]);//基站
					ps.setString(4, l);//位置
					ps.setString(5, infoSplit[8]);//速度	
					ps.setString(6, infoSplit[9]);//电流
					ps.setString(7, infoSplit[10]);//电压
					ps.setString(8, infoSplit[11]);//备用电压
					//ps.setString(9, infoSplit[12]);//里程
					System.out.println(sql1);
					ps.executeUpdate();
					con.commit();
					System.out.println("已新增");
				}
				String reply = "OK";
				pw.write(reply);
				pw.flush();
			}
			pw.close();// 输出流关闭
			socket.close();*/
			
			
			
			/*try {
				Class.forName("com.mysql.jdbc.Driver");// 驱动
			}catch (ClassNotFoundException ex) {
				System.out.println("驱动没有加载");
			}
			String dburl = "jdbc:mysql://localhost:3306/mysql?characterEncoding=UTF-8";
			String user = "root";
			String password = "123456";
			PreparedStatement ps = null;
			try (Connection con = DriverManager.getConnection(dburl, user, password); // 连接
					Statement stmt = con.createStatement();) {
				while ((info = br.readLine()) != null) {
					// 循环读取客户端的信息
					String[] infoSplit = null;
					String l = null;
					infoSplit = info.split(",");
					System.out.println("【"+infoSplit[0] + "】：" + info);
					if (info.length() > 80 ) {
						if(infoSplit[5].length()+infoSplit[7].length()<40){
						String result = connectURL("http://api.map.baidu.com/geoconv/v1/?coords=" + infoSplit[5] + ","
								+ infoSplit[7] + "&from=1&to=5&output=json&ak=HdveE6DXEvvXf9Ppl5Xjwvm73C1hecfX", "");
						String cut1 = result.substring(result.indexOf("x") + 3);
						String[] cut2 = cut1.split(",");
						String cut3 = cut1.substring(cut1.indexOf("y") + 3);
						String[] cut4 = cut3.split("}");
						l =  cut2[0]+ "," + cut4[0];
						String result2 = connectURL("http://api.map.baidu.com/geocoder/v2/?location=" +cut4[0]+ "," + cut2[0]
								+ "&output=json&ak=HdveE6DXEvvXf9Ppl5Xjwvm73C1hecfX", "");
						 road=	result2.split("\"");
						System.out.println(road[45]);
						//{"status":0,"result":{"location":{"lng":110.31800770412998,"lat":25.31193921395791},"formatted_address":"广西壮族自治区桂林市叠彩区清风路","business":"","addressComponent":{"country":"中国","country_code":0,"province":"广西壮族自治区","city":"桂林市","district":"叠彩区","adcode":"450303","street":"清风路","street_number":"","direction":"","distance":""},"pois":[],"poiRegions":[],"sematic_description":"泗洲湾花园东北90米","cityCode":142}}
						}else{
							l="0,0";
							road=null;
						}
						con.setAutoCommit(false);
						String sql1 = "INSERT INTO location_info VALUES(uuid(),?,?,?,NOW(),?,?,'"+road[45]+"')";
						ps = con.prepareStatement(sql1);
						ps.setString(1, infoSplit[0]);
						ps.setString(2, infoSplit[1]);
						ps.setString(3, infoSplit[2]);
						ps.setString(4, l);
						ps.setString(5, infoSplit[8]);
						ps.executeUpdate();
						con.commit();
						System.out.println("已新增");
					}
					String reply = "OK";
					pw.write(reply);
					pw.flush();
				}
				pw.close();// 输出流关闭
				socket.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}*/
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private static final Logger Log = Logger.getLogger(Socket.class);

	public static String connectURL(String dest_url, String commString) {
		String rec_string = "";
		URL url = null;
		HttpURLConnection urlconn = null;
		OutputStream out = null;
		BufferedReader rd = null;
		try {
			url = new URL(dest_url);
			urlconn = (HttpURLConnection) url.openConnection();
			urlconn.setReadTimeout(1000 * 30);
			urlconn.setRequestMethod("POST");
			urlconn.setDoInput(true);
			urlconn.setDoOutput(true);
			out = urlconn.getOutputStream();
			out.write(commString.getBytes("UTF-8"));
			out.flush();
			out.close();
			rd = new BufferedReader(new InputStreamReader(urlconn.getInputStream()));
			StringBuffer sb = new StringBuffer();
			int ch;
			while ((ch = rd.read()) > -1)
				sb.append((char) ch);
			rec_string = sb.toString();
		} catch (Exception e) {
			Log.error(e, e);
			return "";
		} finally {
			try {
				if (out != null) {
					out.close();
				}
				if (urlconn != null) {
					urlconn.disconnect();
				}
				if (rd != null) {
					rd.close();
				}
			} catch (Exception e) {
				Log.error(e, e);
			}
		}
		return rec_string;
	}
}

